package leetcode.code0957;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

	public int[] prisonAfterNDays(int[] cells, int n) {
		int start = 0;
		for (int i = 0; i < cells.length; i++) {
			if (cells[i] == 1) {
				start |= 1 << (7 - i);
			}
		}
		int next = start, p = 0;
		int[] dp = new int[1 << 8];
		Integer[] exist = new Integer[1 << 8];
		dp[p] = next;
		do {
			exist[next] = p;
			p++;
			next = change(next);
			dp[p] = next;
		} while (exist[next] == null && p < n);
		int ans = 0;
		if (p == n) {
			ans = dp[n];
		} else {
			ans = dp[((n - p) % (p - exist[next])) + exist[next]];
		}
		int[] ret = new int[8];
		p = 7;
		while (ans > 0) {
			ret[p--] = (ans & 1);
			ans >>= 1;
		}
		return ret;
	}

	private int change(int start) {
		int ans = 0;
//  	两边一定是0 ，没说清楚啊。是不存在两个，那一个是不是都被啊
//		if (((start >> 6) & 1) == 0) {
//			ans |= 1 << 7;
//		}
//		if (((start >> 1) & 1) == 0) {
//			ans |= 1;
//		}
		// 0,1,0,1,1,0,0,1
		for (int i = 6, rule = 0b10100000; i >= 1; i--, rule >>>= 1) {
			// 一间牢房的两个相邻的房间都被占用或都是空的，那么该牢房就会被占用。
			if ((rule & start) == 0 || (rule & start) == rule) {
				ans |= 1 << i;
			}
		}
		return ans;
	}

	@Override
	public void debug4() {
		H.compare(H.str2array3("[0,0,1,1,0,0,0,0]"), this.prisonAfterNDays(H.str2array3("[0,1,0,1,1,0,0,1]"), 7));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
